//窗口设置
myLib.NS("desktop.win");
myLib.desktop.win={
	winHtml:function(title,url,id){
		return "<div class='windows corner' id="
		+id
		+"><div class='win_title'><b>"
		+title
		+"</b><span class='win_btnblock'><a href='#' class='winMinimize' title='最小化'></a><a href='#' class='winMaximize' title='最大化'></a><a href='#' class='winHyimize' title='还原'></a><a href='#' class='winClose' title='关闭'></a></span></div><iframe frameborder='0' name='myFrame_"
		+id
		+"' id='myFrame_"
		+id
		+"' class='winframe' scrolling='auto' width='100%' src=''></iframe></div>";
		},
	//添加遮障层，修复iframe 鼠标经过事件bug
	iframFix:function(obj){
		obj.each(function(){
			var o=$(this);
			if(o.find('.zzDiv').size()<=0)
			o.append($("<div class='zzDiv' style='width:100%;height:"+(o.innerHeight()-26)+"px;position:absolute;z-index:900;left:0;top:26px;'></div>"));
		});
	},	
	//获取当前窗口最大的z-index值
	maxWinZindex:function($win){
		return Math.max.apply(null, $.map($win, function (e, n) {
        if ($(e).css('position') == 'absolute')
            return parseInt($(e).css('z-index')) || 1;
        }));
	},
	//获取当前最顶层窗口		
	findTopWin:function($win,maxZ){
		var topWin = null;
		$win.each(function(index){
		   if($(this).css("z-index")==maxZ){
			   topWin=$(this);
			   return false;
			   } 
		   });
		return topWin;
		},		
	//关闭窗口	
	closeWin:function(obj) {
		
		//调用检查是否保存的方法
		var tab = $("#task_lb_wrap a.selectTab");//console.log(tab);
		var tabWin = getTabDataWin(tab.data("options").title);
		//console.log(tabWin);
		//tabWin.checkIsSaveBeforeClose();
		if(tabWin && tabWin.checkIsSaveBeforeClose) {
			tabWin.checkIsSaveBeforeClose();
		}
		
		var _this=this
			,$win=$('div.windows').not(".hideWin")
			,maxZ
			,topWin;
 		myLib.desktop.taskBar.delWinTab(obj);
		obj.hide(200,function(){
			$(this).remove();
		});
		//当关闭窗口后寻找最大z-index的窗口并使其出入选择状态
		if($win.size()>1){
			maxZ=_this.maxWinZindex($win.not(obj));
			topWin=_this.findTopWin($win,maxZ);
			_this.switchZindex(topWin);
			//console.log(maxZ);
		}
	},
	//最小化窗口	
	minimize:function(obj){
		var _this=this,$win=$('div.windows').not(".hideWin"),maxZ,topWin,objTab;
		//obj.hide();
		obj.css({"left":obj.position().left-10000,"visibility":"hidden"}).addClass("hideWin");
		//最小化窗口后，寻找最大z-index窗口至顶
		if($win.size()>1){
		maxZ=_this.maxWinZindex($win.not(obj));
		topWin=_this.findTopWin($win,maxZ);
		_this.switchZindex(topWin);
		}else{
			objTab=myLib.desktop.taskBar.findWinTab(obj);
			objTab.removeClass('selectTab').addClass('defaultTab');
			}
		},	
	//最大化窗口函数	
	maximizeWin:function(obj){
		var myData=myLib.desktop.getMydata(),
		    panel=$("#desktopInnerPanel").offset(), 
		    myData2=obj.data(),
		    winLocation=myData2.winLocation,
		    wh=myData.winWh;//获取当前document宽高
		//console.log(parseInt(winLocation['left']));
		obj
//		.css({'width':wh['w'],'height':wh['h']-40,'left':-panel.left,'top':-panel.top+40})
		.css({'width':wh['w'],'height':wh['h']-40,'left':parseInt(winLocation['left'])-85,'top':parseInt(winLocation['top'])-30})
		.draggable("disable")
		.resizable("disable")
		.fadeTo("fast",1)
		.find(".winframe")
		.css({'width':wh['w'],'height':wh['h']-26-40});
		//easyui-tab自适应
		obj.find(".winframe")[0].contentWindow.window.$(".easyui-tabs").tabs({width:wh['w']-2,height:"auto"});
	},
	//还原窗口函数	
	hyimizeWin:function(obj){
		var myData=obj.data(),
		    winLocation=myData.winLocation;//获取窗口最大化前的位置大小
		obj.css({'width':winLocation['w'],'height':winLocation['h'],'left':winLocation['left'],'top':winLocation['top']})
		.draggable( "enable" )
		.resizable( "enable" ) 
		.find(".winframe")
		.css({'width':winLocation['w'],'height':winLocation['h']-26});
		//easyui-tab自适应
		obj.find(".winframe")[0].contentWindow.window.$(".easyui-tabs").tabs({width:winLocation['w']-2,height:"auto"});
	},	
	//交换窗口z-index值		
	switchZindex:function(obj){
		var myData=myLib.desktop.getMydata()
		    ,$topWin=myData.topWin
			,$topWinTab=myData.topWinTab
		    ,curWinZindex=obj.css("z-index")
			,maxZ=myData.maxZindex
			,objTab=myLib.desktop.taskBar.findWinTab(obj);
		if(!$topWin.is(obj)){
			obj.css("z-index",maxZ);
			objTab.removeClass('defaultTab').addClass('selectTab');
			$topWin.css("z-index",curWinZindex);
			$topWinTab.removeClass('selectTab').addClass('defaultTab');
			this.iframFix($topWin);
			//setTimeout(function(){$topWin.find(".winframe")[0].contentWindow.focus();},0);
			//$topWin.show();
			//更新最顶层窗口对象
			//console.log(objTab);
			//console.log(objTab.data("options").index);
			//将面板旋转到待打开窗口的位置
//			var myData=myLib.desktop.getMydata(),
//			$navBar=myData.panel.navBar,
//			$innerPanel=myData.panel.desktopPanel.innerPanel,
//			$navTab=$navBar.find("a"),
//			$deskIcon=myData.panel.desktopPanel['deskIcon'],
//			desktopWidth=$deskIcon.width(),
//			lBarWidth=myData.panel.lrBar["_this"].outerWidth();
//			myLib.desktop.deskIcon.desktopMove($innerPanel,$deskIcon,$navTab,0,desktopWidth+lBarWidth,objTab.data("options").index);
			$('body').data("topWin",obj).data("topWinTab",objTab);
		}
	},
		
	//新建一个窗口
	//FIXME
    newWin:function(options){
		var myData=myLib.desktop.getMydata(),
		    wh=myData.winWh,//获取当前document宽高
			$windows=$("div.windows"),
			_this=this,
			curwinNum=myLib._is(myData.winNum,"Number")?myData.winNum:0;//判断当前已有多少窗口
			_this.iframFix($windows);
		//默认参数配置
        var defaults = {
            WindowTitle:          null,
			WindowsId:            null,
            WindowPositionTop:    'center',                          /* Posible are pixels or 'center' */
            WindowPositionLeft:   'center',                          /* Posible are pixels or 'center' */
            WindowWidth:          $(window).width()-100,           /* Only pixels */
            WindowHeight:         $(window).height()-160,           /* Only pixels */
            WindowMinWidth:       250,                               /* Only pixels */
            WindowMinHeight:      250,                               /* Only pixels */
		    iframSrc:             null,                              /* 框架的src路径*/ 
            WindowResizable:      true,                              /* true, false*/
            WindowMaximize:       true,                              /* true, false*/
            WindowMinimize:       true,                              /* true, false*/
            WindowClosable:       true,                              /* true, false*/
            WindowDraggable:      true,                              /* true, false*/
            WindowStatus:         'regular',                         /* 'regular', 'maximized', 'minimized' */
            WindowAnimationSpeed: 500,
            WindowAnimation:      'none',
            pageindex:			  '',
            imgclass:			  'imgIcon icon-default'
        };
		var options = $.extend(defaults, options);
		//判断窗口位置，否则使用默认值
		//var dxy=Math.floor((Math.random()*10))-40;
		var dxy=-40;
		var panelLeft=$("#desktopInnerPanel").position();
//		console.log(options['WindowsId']);
		var desk=$("#deskIcon_"+options['WindowsId']).parent();
		//console.log(desk);
		var i=desk.index("ul.deskIcon");
		if(options['WindowsId'].indexOf("teskbartab")>=0){
			//console.log(options['WindowTitle']);
			//console.log($("#applemenu img.desktop_icon_over_b"));
			//如果没有放大的一级模块，说明是消息的内容在桌面显示
			if($("#applemenu img.desktop_icon_over_b").length){
				i=$("#applemenu img.desktop_icon_over_b").data("index");
			}else{
				i = $('#desktopInnerPanel ul').length - 1;
			}
		}else{
			//console.log($("#menu_"+options['WindowsId']));
			//是否是有下拉菜单的
			if($("#menu_"+options['WindowsId']).length) {
//				var xx=$("#"+options['WindowsId']).attr('myparentid');
//				desk=$("#deskIcon_" + xx).parent();
				i = $("#menu_"+options['WindowsId']).attr('_page');
			}
			
			if(i<0) {
				i = $('#desktopInnerPanel ul').length - 1;
				//将面板旋转到待打开窗口的位置
				var myData=myLib.desktop.getMydata(),
				$navBar=myData.panel.navBar,
				$innerPanel=myData.panel.desktopPanel.innerPanel,
				$navTab=$navBar.find("a"),
				$deskIcon=myData.panel.desktopPanel['deskIcon'],
				desktopWidth=$deskIcon.width(),
				lBarWidth=myData.panel.lrBar["_this"].outerWidth();
				myLib.desktop.deskIcon.desktopMove($innerPanel,$deskIcon,$navTab,0,desktopWidth+lBarWidth,i);
			}
		}
		panelLeft.left = -(myData.panel.desktopPanel['deskIcon'].width()+myData.panel.lrBar["_this"].outerWidth())*i;
		//计算弹出的新窗口的绝对定位位置
		var wLeft=myLib._is(options['WindowPositionLeft'],"Number")?
				options['WindowPositionLeft']+dxy-panelLeft.left:(wh['w']-options['WindowWidth'])/2+dxy-panelLeft.left;
		var wTop=myLib._is(options['WindowPositionTop'],"Number")?
				options['WindowPositionTop']+dxy/2:(wh['h']-options['WindowHeight'])/2+dxy/2-40;
		//给窗口赋予新的z-index值
		var zindex=curwinNum+500;
		var id="myWin_"+options['WindowsId'];//根据传来的id将作为新窗口id
 		$('body').data("winNum",curwinNum+1);//更新窗口数量
		//判断如果此id的窗口存在，则不创建窗口
 		//如果窗口不存在
 		//console.log(options['WindowsId']);
		if($("#"+id).size()<=0&&options['WindowsId']!='mydesk'){
			//在任务栏里添加tab
			
			myLib.desktop.taskBar.addWinTab(options['WindowTitle'],options['WindowsId'],options['imgclass'],i);
			//setTimeout(function(){$(_this.winHtml(options['WindowTitle'],options['iframSrc'],id)).appendTo('#desktopInnerPanel');},3);
			//初始化新窗口并显示
			//console.log($(_this.winHtml(options['WindowTitle'],options['iframSrc'],id)));
			/*var desk=null,
			i=null;	//判断窗口在那个桌面区域
			console.log(id);
	    	desk=$("#"+id).parent();
	    	if(iconId.indexOf("menu")>=0){
				var xx=$("#"+iconId).attr('myparentid');
				desk=$("#deskIcon" + xx).parent();
			}
			else if(iconId.indexOf("deskIcon")>=0) {
			    	
						desk=$("#"+iconId).parent();
						//console.log(desk);
					//i=desk.index("ul.deskIcon");
			    }else{
			    	var x=$("#menu"+iconId).attr("myparentid");
			    	//console.log($("#menu"+iconId).attr("myparentid"));
			    	desk=$("#deskIcon"+x).parent();
					//i=desk.index("ul.deskIcon");
			    }
			i=desk.index("ul.deskIcon");*/
	    	//console.log(i);
			//将面板旋转到待打开窗口的位置
			var myData=myLib.desktop.getMydata(),
			$navBar=myData.panel.navBar,
			$innerPanel=myData.panel.desktopPanel.innerPanel,
			$navTab=$navBar.find("a"),
			$deskIcon=myData.panel.desktopPanel['deskIcon'],
			desktopWidth=$deskIcon.width(),
			lBarWidth=myData.panel.lrBar["_this"].outerWidth();
			myLib.desktop.deskIcon.desktopMove($innerPanel,$deskIcon,$navTab,0,desktopWidth+lBarWidth,i);
			//将新窗口添加至面板中
			$(_this.winHtml(options['WindowTitle'],options['iframSrc'],id)).appendTo('#desktopInnerPanel');
			//console.log(options['WindowTitle']);
			//初始化窗口打开关闭最小化按钮
			var $newWin=$("#"+id)
			,$icon=$("#"+options['WindowsId'])
			,$iconOffset=$icon.offset()
			,$fram=$newWin.find(".winframe")
			,$winTitle=$newWin.find(".win_title")
			,winMaximize_btn=$newWin.find('a.winMaximize')//最大化按钮
			,winMinimize_btn=$newWin.find('a.winMinimize')//最小化按钮
			,winClose_btn=$newWin.find('a.winClose')//关闭按钮
			,winHyimize_btn=$newWin.find('a.winHyimize');//还原按钮
			winHyimize_btn.hide();
			if(!options['WindowMaximize']) winMaximize_btn.hide();
			if(!options['WindowMinimize']) winMinimize_btn.hide();
			if(!options['WindowClosable']) winClose_btn.hide();
			//存储窗口最大的z-index值,及最顶层窗口对象
			$('body').data({"maxZindex":zindex,"topWin":$newWin});
			//判断窗口是否启用动画效果
//			console.log(options.WindowAnimation);
			if(options.WindowAnimation=='none'){
				$newWin
				.css({"width":options['WindowWidth'],"height":options['WindowHeight'],"left":wLeft,"top":wTop,"z-index":zindex})
				.addClass("loading")
				.show(10,function(){
					$(this).find(".winframe").attr("src",options['iframSrc']).load(function(){
						$(this).show();
						//easyui-tab自适应
						$(this)[0].contentWindow.window.$(".easyui-tabs").tabs({width:options['WindowWidth']-2,height:"auto"});
					});
				});
			}else{
				$newWin
				.css({"left":$iconOffset.left,"top":$iconOffset.top,"z-index":zindex})
				.addClass("loading")
				.show()
				.animate({ 
					width:options['WindowWidth'],
					height:options['WindowHeight'],
					top:wTop, 
					left:wLeft}
					,100,function(){
						$(this).find(".winframe").attr("src",options['iframSrc']).load(function(){
							$(this).show();
							//easyui-tab自适应
							$(this)[0].contentWindow.window.$(".easyui-tabs").tabs({width:options['WindowWidth']-2,height:"auto"});
						});
					});
 			}
	        $newWin
			//存储窗口当前位置大小
			.data('winLocation',{
				  'w':options['WindowWidth'],
				  'h':options['WindowHeight'],
				  'left':wLeft,
				  'top':wTop
				  })
			//鼠标点击，切换窗口，使此窗口显示到最上面
			.bind({
				"mousedown":function(event){  
				_this.switchZindex($(this));
						},
				"mouseup":function(){
				$(this).find('.zzDiv').remove();
							}		
					})
			.find(".winframe")
			.css({"width":options['WindowWidth'],"height":options['WindowHeight']-26});
	 		 //调用窗口拖动,参数可拖动的范围上下左右，窗口id和，浏览器可视窗口大小
			 if(options['WindowDraggable']){
			   _this.drag([0,0,wh['w']-options['WindowWidth']-10,wh['h']-options['WindowHeight']-35],$newWin,wh);
			  }
			//调用窗口resize,传递最大最小宽度和高度，新窗口对象id，浏览器可视窗口大小
			if(options['WindowResizable']){
			   _this.resize(options['WindowMinWidth'],options['WindowMinHeight'],wh['w']-wLeft,wh['h']-wTop-35,$newWin,wh);
			 }
	//        console.log($($newWin.find("iframe").context).find("a.tabs-inner")[0]);
	//        $($newWin.find("iframe").context).find("a.tabs-inner")[0].click();
	//        $($($newWin.find("iframe").context).find("li.tabs-selected")[0]).trigger("click");
			//双击窗口标题栏
			$winTitle.dblclick(function(){
				var hasMaximizeBtn=$(this).find(winMaximize_btn);
				if(!hasMaximizeBtn.is(":hidden")){
					winMaximize_btn.trigger("click");
				}else{
					winHyimize_btn.trigger("click");
				}
			});
			//窗口最大化，最小化，及关闭
			winClose_btn.click(function(event){
				 event.stopPropagation();
				 //console.log($newWin);
				 _this.closeWin($newWin);
			});
			//最大化
			winMaximize_btn.click(function(event){
				 event.stopPropagation();			   
				 if(options['WindowStatus']=="regular"){								 
					 _this.maximizeWin($newWin);
					 $(this).hide();
					 winHyimize_btn.show();
					 options['WindowStatus']="maximized";
					 $("#desktopPanel").css("z-index",95);
				 }
			});
			//如果浏览器窗口大小改变，则更新窗口大小
			$(window).wresize(function(){
				if(options['WindowStatus']=="maximized"){	   
					_this.maximizeWin($newWin);
				}
			});
			//还原窗口
			winHyimize_btn.click(function(event){
				 event.stopPropagation();				  
				 if(options['WindowStatus']=="maximized"){								 
					 _this.hyimizeWin($newWin);
					 $(this).hide();
					 winMaximize_btn.show();
					 options['WindowStatus']="regular";
					 $("#desktopPanel").css("z-index",70);
				 }		  
			});
			//最小化窗口
			winMinimize_btn.click(function(){
				_this.minimize($newWin);		   
			});
		}else{//如果已经创建新窗口
  						 //alert();
			$("#task_lb a").each(function(i){
				//console.log($(this).data("options").title);
				//console.log(options['WindowTitle']);
				if($(this).data("options").title==options['WindowTitle']){
					$(this).trigger("click");
				}
			});
        	 //$("#task_lb a:contains('"+options['WindowTitle']+"')").trigger("click");
						 //如果已存在此窗口，判断是否隐藏
//					     var wins=$("#"+id),objTab=myLib.desktop.taskBar.findWinTab(wins);
//						 if(wins.is(":hidden")){
//							  wins.show();
//							  objTab.removeClass('defaultTab').addClass('selectTab');//当只有一个窗口时
//						      myLib.desktop.win.switchZindex(wins);
//							 }else{
//								 }
		}
	},
	upWinResize_block:function(win){
		    
			//更新窗口可改变大小范围,wh为浏览器窗口大小
            var offset=win.offset();
		    win.resizable({'maxWidth':$(window).width()-offset.left-10,'maxHeight':$(window).height()-offset.top-35});
	},
	//窗口拖动
	//FIXME 
 	drag:function(arr,$newWin,wh){
		var _this=this;
		$newWin
		.draggable({ 
		    handle:'div.win_title',
		    iframeFix:false,
			scroll: false,
			onBeforeDrag:function(event){
				//myData.panel.desktopPanel.innerPanel.draggable("disable");
				$("#desktopInnerPanel").draggable("disable");
				//console.log($("#desktopInnerPanel"));
			},
			onStartDrag:function(event){
				_this.iframFix($(this));
				$("#desktopPanel").css("z-index",95);
			},
			onStopDrag:function(event) {
				$("#desktopInnerPanel").draggable("enable");
				$("#desktopPanel").css("z-index",70);	
				var obj_this=$(this);	
	 			//计算可拖曳范围
				_this.upWinResize_block(obj_this);
			    obj_this
				//更新窗口存储的位置属性
				.data('winLocation',{
				'w':obj_this.width(),
				'h':obj_this.height(),
				'left':obj_this.css("left"),
				'top':obj_this.css("top")
				})
				.find('.zzDiv')
				.remove();
				if(event.pageY>wh.h-50){
					$(this).css("top",event.pageY-90);
	 		    }else if(event.pageY<-35){
					$(this).css("top",-35);
				}
	         }
		});
//		.bind("dragstart",function(event,ui){alert();
// 					_this.iframFix($(this));
//					$("#desktopPanel").css("z-index",95);
//						  })
//		.bind( "dragstop", function(event, ui) {
//			$("#desktopPanel").css("z-index",70);	
//			var obj_this=$(this);	
// 			//计算可拖曳范围
//			_this.upWinResize_block(obj_this);
//		    obj_this
//			//更新窗口存储的位置属性
//			.data('winLocation',{
//			'w':obj_this.width(),
//			'h':obj_this.height(),
//			'left':obj_this.css("left"),
//			'top':obj_this.css("top")
//			})
//			.find('.zzDiv')
//			.remove();
//			if(event.pageY>wh.h-50){
//							  $(this).css("top",event.pageY-90);
// 		    }else if(event.pageY<-35){
//							  $(this).css("top",-35);
//								  }
//         }); 
		  $("div.win_title").css("cursor","move");
	},
	resize:function(minW,minH,maxW,maxH,$newWin,wh){
		var _this=this;
		$newWin
		.resizable({
		minHeight:minH,
		minWidth:minW,
		containment:'document',
		maxWidth:maxW,
		maxHeight:maxH
		})
		.css("position","absolute")
		.bind( "resize", function(event, ui) {
			var h=$(this).innerHeight(),w=$(this).innerWidth(); 	
 			 _this.iframFix($(this));
			//拖曳改变窗口大小，更新iframe宽度和高度，并显示iframe
			$(this).children(".winframe").css({"width":w,"height":h-26});
        })
	   .bind( "resizestop", function(event, ui) {					 
			var obj_this=$(this);
 			var h=obj_this.innerHeight(),w=obj_this.innerWidth();
		    obj_this
			//更新窗口存储的位置属性
			.data('winLocation',{
			'w':w,
			'h':h,
			'left':obj_this.css("left"),
			'top':obj_this.css("top")
			  })
			 //删除遮障iframe的层
			.find(".zzDiv")
			.remove();
       });
	}
};